package cn.xinyangtong.manager.service.impl;

import cn.xinyangtong.common.pojo.DataResult;
import cn.xinyangtong.common.pojo.DefaultResult;
import cn.xinyangtong.manager.entity.ItemParam;
import cn.xinyangtong.manager.mapper.ItemParamMapper;
import cn.xinyangtong.manager.service.ItemParamService;
import cn.xinyangtong.mapper.TbItemParamMapper;
import cn.xinyangtong.pojo.TbItemParam;
import cn.xinyangtong.pojo.TbItemParamExample;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 商品规格参数模板
 * Created by fengbo on 2017/6/16.
 */
@Service("itemParamService")
public class ItemParamServiceImpl implements ItemParamService {

    private final Logger log = LoggerFactory.getLogger(ItemParamServiceImpl.class);

    @Autowired
    private TbItemParamMapper tbItemParamMapper;
    @Autowired
    private ItemParamMapper itemParamMapper;

    //根据itemCatID查询规格参数模板
    @Override
    public DefaultResult getItemParamByCid(Long cid) {
        TbItemParamExample example = new TbItemParamExample();
        TbItemParamExample.Criteria criteria = example.createCriteria();
        criteria.andItemCatIdEqualTo(cid);
        List<TbItemParam> list = tbItemParamMapper.selectByExampleWithBLOBs(example);//包含大文本时
        //判断是否查询到结果
        if (list != null && list.size() > 0) {
            return DefaultResult.ok(list.get(0));
        }
        return DefaultResult.ok();
    }

    //查询商品规格参数模板列表
    @Override
    public DataResult<ItemParam> getItemParamList(Integer page, Integer rows) {
        PageHelper.startPage(page, rows);
        List<ItemParam> list = itemParamMapper.selectItemParamList();
        PageInfo<ItemParam> pageInfo = new PageInfo<>(list);

        DataResult<ItemParam> result = new DataResult<>();
        result.setRows(list);
        result.setTotal(pageInfo.getTotal());
        return result;
    }

    // 添加规格参数模板
    @Override
    public DefaultResult addItemParam(TbItemParam itemParam) {
        //补全pojo
        Date date = new Date();
        itemParam.setCreated(date);
        itemParam.setUpdated(date);
        //插入到规格参数模板
        int num = tbItemParamMapper.insert(itemParam);
        if (num <= 0) {
            log.error("Insert ItemParam Fail! ItemParamId = " + itemParam.getId());
            return DefaultResult.build(500,"添加规格参数失败！");
        }
        return DefaultResult.ok();
    }
}
